package com.server.llh.llhserverwork.adapter.base;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.server.llh.llhserverwork.port.HolderOnclickInterface;

import java.util.List;


public abstract class ListViewDataAdapterBase<T> extends BaseAdapter {
    HolderOnclickInterface holderOnclickInterface;
    protected ViewHolderCreator<T> mViewHolderCreator;
    
    public void setViewHolderClass(final Object enclosingInstance, final Class<?> cls, final Object... args) {
        mViewHolderCreator = ViewHolderCreator.create(enclosingInstance, cls, args);
    }
    public void registCallBack(HolderOnclickInterface holderOnclickInterface){
        this.holderOnclickInterface=holderOnclickInterface;
    }
    @SuppressWarnings("unchecked")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        T itemData = getItem(position);
        ViewHolderBase<T> viewHolder = null;
        if (convertView == null || (!(convertView.getTag() instanceof ViewHolderBase<?>))) {
            viewHolder = createViewHolder(position);
            if (viewHolder != null) {
                convertView = viewHolder.createView(LayoutInflater.from(parent.getContext()));
                if (convertView != null) {
                 convertView.setTag(viewHolder);
                }
            }
        } else {
            viewHolder = (ViewHolderBase<T>) convertView.getTag();
        }
        if (viewHolder != null) {
            viewHolder.setItemData(position, convertView);
            viewHolder.showData(position, itemData);
            viewHolder.showData(position, itemData,holderOnclickInterface);
        }
        return convertView;
    }

    @Override
    public abstract T getItem(int position);
    
    public abstract void update(List<T> list);
    
    private ViewHolderBase<T> createViewHolder(int position) {
        if (mViewHolderCreator == null) {
            throw new RuntimeException("view holder creator is null");
        }
        if (mViewHolderCreator != null) {
            return mViewHolderCreator.createViewHolder(position);
        }
        return null;
    }
}
